import 'package:flutter/material.dart';
import 'package:flutter_business_1803a/bean/category_child_opt_result.dart';
import 'package:flutter_business_1803a/bean/category_goods_opt_list_result.dart';
import 'package:flutter_business_1803a/bean/category_parent_opt_result.dart';
import 'package:flutter_business_1803a/provide/provide_child_category.dart';
import 'package:flutter_business_1803a/router/application.dart';
import 'package:flutter_business_1803a/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provide/provide.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  List<GoodsOptListListBean> parentList;

  var listIndex = 0;

  //请求左侧一级列表
  Future _getCategory() async {
    await request('getGoodsOpt', {'parent_opt_id': 0}).then((val) {
      parentList = CategoryParentOptResult
          .fromJson(val)
          .entity
          .goodsOptGetResponse
          .goodsOptList;
    });
    return parentList;
  }

  //获取二级列表的网络请求
  void _getCategoryChild(optId) async {
    await request('getGoodsOpt', {'parent_opt_id': optId}).then((val) {
      //获取了数据源之后,如果使用有状态控件,则需要使用setState方法来重新build刷新出数据
      //存到Provide中去
      Provide.value<ChildCategory>(context)
          .setChildCategory(CategoryChildOptResult
          .fromJson(val)
          .entity);
      _getCategoryGoodsList(
          1, Provide
          .value<ChildCategory>(context)
          .childCategoryList[0].optId);
      Provide.value<ChildCategory>(context).changeChildIndex(0);
    });
  }

  //获取三级列表的方法
  void _getCategoryGoodsList(page, optId) async {
    var data = {'page': page, 'opt_id': optId};
    await request('categoryGoods', data).then((val) {
      // print(GoodsOptListResult.fromJson(val).entity.goods_search_response.goods_list.length);
      Provide.value<ChildCategory>(context).setCategoryGoodsList(
          GoodsOptListResult
              .fromJson(val)
              .entity
              .goods_search_response
              .goods_list);
    });
  }

  Widget _leftInkWell(index) {
    bool isClick = false;
    isClick = (index == listIndex) ? true : false;
    return InkWell(
      onTap: () {
        setState(() {
          listIndex = index;
        });
        _getCategoryChild(parentList[index].optId);
        Provide.value<ChildCategory>(context).setOptId(parentList[index].optId);
        Provide.value<ChildCategory>(context).rePage();
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: EdgeInsets.only(left: 20, top: 15),
        decoration: BoxDecoration(
            color: isClick ? Colors.black26 : Colors.white,
            border:
            Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          parentList[index].optName,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }

  Widget _leftCategoryNav() {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _leftInkWell(index);
        },
        itemCount: parentList.length,
      ),
    );
  }

  @override
  void initState() {
    _getCategory();
    _getCategoryChild(14);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, height: 1334, width: 750);
    return Scaffold(
      appBar: AppBar(
        title: Text('分类'),
      ),
      body: Container(
          child: Row(
            children: <Widget>[
              FutureBuilder(
                future: _getCategory(),
                builder: (context, val) {
                  if (val.hasData) {
                    return _leftCategoryNav();
                  } else {
                    return Center(
                      child: Text('加载中'),
                    );
                  }
                },
              ),
              Column(
                children: <Widget>[
                  //右侧上方小导航
                  RightCategoryNav(),
                  //右侧下方具体商品列表
                  CategoryGoodsList(),
                ],
              )
            ],
          )),
    );
  }
}

//右侧上方导航栏
class RightCategoryNav extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Provide<ChildCategory>(
      builder: (context, child, childCategory) {
        return Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(570),
          decoration: BoxDecoration(
              color: Colors.white,
              border:
              Border(bottom: BorderSide(width: 1, color: Colors.black12))),
          child: ListView.builder(
            itemBuilder: (context, index) {
              return _rightInkWell(
                  childCategory.childCategoryList[index], context, index);
            },
            itemCount: childCategory.childCategoryList.length,
            scrollDirection: Axis.horizontal,
          ),
        );
      },
    );
  }

  //右侧导航的item
  Widget _rightInkWell(EntityListBean item, context, index) {
    bool isClick = false;
    isClick = (index == Provide
        .value<ChildCategory>(context)
        .childIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        _getCategoryGoodsList(1, item.optId, context);
        Provide.value<ChildCategory>(context).setOptId(item.optId);
        Provide.value<ChildCategory>(context).rePage();
        Provide.value<ChildCategory>(context).changeChildIndex(index);
      },
      child: Container(
        color: isClick ? Colors.pink : Colors.white,
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.optName,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }

  void _getCategoryGoodsList(page, optId, context) async {
    var data = {'page': page, 'opt_id': optId};
    await request('categoryGoods', data).then((val) {
      Provide.value<ChildCategory>(context).setCategoryGoodsList(
          GoodsOptListResult
              .fromJson(val)
              .entity
              .goods_search_response
              .goods_list);
    });
  }
}

//右侧商品列表
class CategoryGoodsList extends StatelessWidget {
  void _getCategoryGoodsList(page, optId, context) async {
    var data = {'page': page, 'opt_id': optId};
    await request('categoryGoods', data).then((val) {
      var goodsList = GoodsOptListResult
          .fromJson(val)
          .entity
          .goods_search_response
          .goods_list;
      if (goodsList == null) {
        Provide.value<ChildCategory>(context).changeNoMore('没有更多了');
      } else {
        Provide.value<ChildCategory>(context).addGoodsList(goodsList);
      }
    });
  }

  //商品图片
  Widget _goodsImage(index, context) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(Provide
          .value<ChildCategory>(context)
          .categoryGoodsList[index]
          .goods_image_url),
    );
  }

  //商品名称
  Widget _goodsName(index, context) {
    return Container(
      width: ScreenUtil().setWidth(370),
      padding: EdgeInsets.all(5.0),
      child: Text(
        Provide
            .value<ChildCategory>(context)
            .categoryGoodsList[index]
            .goods_name,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  //商品价格
  Widget _goodsPrice(index, context) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            '价格:¥${Provide
                .value<ChildCategory>(context)
                .categoryGoodsList[index].min_group_price / 100}',
            style:
            TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            '原价:¥${Provide
                .value<ChildCategory>(context)
                .categoryGoodsList[index].min_normal_price / 100}',
            style: TextStyle(
                color: Colors.black26, decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  //构建商品的item
  Widget _listWidgetItem(index, context) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(context, '/detail?id=${Provide
            .value<ChildCategory>(context)
            .categoryGoodsList[index].goods_id}');
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
            Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
        child: Row(
          children: <Widget>[
            _goodsImage(index, context),
            Column(
              children: <Widget>[
                _goodsName(index, context),
                _goodsPrice(index, context)
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var scrollController = ScrollController();
    return Provide<ChildCategory>(
      builder: (context, child, data) {
        try {
          if (Provide
              .value<ChildCategory>(context)
              .page == 1) {
            scrollController
                .jumpTo(0.0); //如果当前时切换后的第一页数据,则让listView滚动到第一个item的位置
          }
        } catch (e) {
          print('进入页面第一次初始化$e');
        }
        return Expanded(
          child: Container(
            width: ScreenUtil().setWidth(570),
            child: EasyRefresh(
              child: ListView.builder(
                controller: scrollController,
                itemBuilder: (context, index) {
                  return _listWidgetItem(index, context);
                },
                itemCount: Provide
                    .value<ChildCategory>(context)
                    .categoryGoodsList
                    .length,
              ),
              footer: ClassicalFooter(
                  bgColor: Colors.white,
                  textColor: Colors.pink,
                  infoColor: Colors.pink,
                  showInfo: true,
                  noMoreText: Provide
                      .value<ChildCategory>(context)
                      .noMoreText,
                  infoText: '加载中',
                  loadReadyText: '上拉加载',
                  loadedText: '加载完成',
                  loadingText: '正在加载',
                  loadText: '上拉加载'),
              onLoad: () async {
                Provide.value<ChildCategory>(context).addPage();
                _getCategoryGoodsList(
                    Provide
                        .value<ChildCategory>(context)
                        .page,
                    Provide
                        .value<ChildCategory>(context)
                        .optId,
                    context);
              },
            ),
          ),
        );
      },
    );
  }
}
